//
//  Element.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-7-5.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "Element.h"


@implementation Element

/**
 * 快捷方式，指定名称创建元素
 */
+ (id)elementWithName:(NSString *)eName{
	return [[[Element alloc] initWithName:eName] autorelease];
}

/**
 * 初始化元素
 */
- (id)initWithName:(NSString *)eName{
	if(self = [super init]){
		attributes = [[NSMutableDictionary alloc] init];
		elementName = [eName copy];
	}
	return self;
}

/**
 * 获取节点名称
 */
- (NSString *)getNodeName{
	return elementName;
}

- (NSInteger)nodeType{
	return ELEMENT_NODE;
}

- (NSDictionary *)getAttributes{
	NSDictionary *ret = nil;
	// TODO 主要是避免结束元素还要返回 attribute
	if([attributes count] > 0){
		ret = attributes; //[NSDictionary dictionaryWithDictionary:attributes];
	}
	return ret;
}

/**
 * 设置属性
 */
- (void)setAttributes:(NSDictionary *)attributeDict{
	if(attributeDict){
		// 旧的数据被 removeAll 新的被赋值过来
		[attributes setDictionary:attributeDict];
	}
}

/**
 * 获取属性，如果不存在，那么返回 nil
 */
- (NSString *)getAttribute:(NSString *)name{
	NSString *ret = nil;
	if([attributes count] > 0){
		ret = [attributes objectForKey:name];
	}
	return ret;
}


/**
 * 通过名称来获取元素
 * 取当前文档中的，所有以 ename命名的一级子元素
 */
-(NSArray *)getElementsByName:(NSString *)ename{
	NSMutableArray *ret = nil;
	int cnum = [childs count];
	if(cnum > 0){
		// TODO 查找以ename命名的子元素
		Node *node = nil;
		NSString *nname = nil;
		ret = [[[NSMutableArray alloc] init] autorelease];
		for (int i = 0; i < cnum; i++) {
			node = (Node *)([childs objectAtIndex:i]);
			nname = [node getNodeName];
			if([nname isEqualToString:ename]){
				[ret addObject:node];
			}
		}
		if([ret count] == 0){
			ret = nil;
		}
	}
	return ret;
}


- (void)dealloc{
	if(attributes != nil){
		if([attributes count] > 0){
			[attributes removeAllObjects];
		}
		[attributes release];
	}
	[elementName release];
	[super dealloc];
}

@end
